import { mountComponent, usePopupState } from '../utils';
import FanDialog from './dialog.vue';
import { ComponentPublicInstance } from 'vue'

interface optionsType{
  title?: string
  message?: string
  cancelText?: string
  cancelColor?: string
  showCancel?: boolean
  confirmText?: string
  confirmColor?: string
  callback?: null | ((n: 'cancel' | 'confirm') => any)
}

const defaultOptions: optionsType = {
  title: '',
  message: '',
  cancelText: '取消',
  cancelColor: '#84878F',
  showCancel: false,
  confirmText: '确定',
  confirmColor: '#F7931E',
  callback: null,
};


let instance: null | ComponentPublicInstance;

function parseOptions(message : optionsType | string) {
  if (typeof message === 'object') return message;
  return { message: message ? String(message) : '' };
}

const createInstance = () => {
  const Wrapper = {
    setup() {
      const { state, toggle } = usePopupState();
      return () => <FanDialog {...state} onUpdate:show={toggle} />;
    },
  };

  ({ instance } = mountComponent((Wrapper as any)));
};

export const dialog = (options: optionsType | string) => {
  return new Promise((resolve, reject) => {
    if (!instance) {
      createInstance();
    }

    const parsedOptions = parseOptions(options);

    (instance as any).open({
      ...defaultOptions,
      ...parsedOptions,
      callback: (action: 'cancel' | 'confirm') => {
        console.log(action);
        (action === 'confirm' ? resolve : reject)(action);
      },
    });
  });
};

dialog.confirm = (options: optionsType | string) => {
  const parsedOptions = parseOptions(options);
  return dialog({ ...parsedOptions, showCancel: true });
};
